package ciicos.controller;

import ciicos.service.LineLinePlaceRelationService;
import ciicos.service.LinePlaceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ciicos.base.ActionResult;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.exception.DataException;
import org.springframework.transaction.annotation.Transactional;
import ciicos.model.lineline.*;
import ciicos.model.lineline.LineLinePagination;
import ciicos.entity.*;
import ciicos.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ciicos.entity.LineLineEntity;
import ciicos.service.LineLineService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
import java.io.IOException;
import ciicos.util.GeneraterSwapUtil;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 线缆管理
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 企业研发中心
 * @日期： 2025-10-03
 */
@Slf4j
@RestController
@Api(tags = "线缆管理", value = "line")
@RequestMapping("/api/line/LineLine")
public class LineLineController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private LineLineService lineLineService;

    @Autowired
    private DataDicUtil dataDicUtil;

    @Autowired
    private LineLinePlaceRelationService lineLinePlaceRelationService;

    @Autowired
    private LinePlaceService linePlaceService;


    /**
     * 线缆统计-数量
     *
     * @param
     * @return
     */
    @ApiOperation("线缆统计-数量")
    @PostMapping("/count")
    public ActionResult count() throws IOException {
        //树形判断是否有参数，有参数不造树
        long count = lineLineService.count();
        return ActionResult.success(count);
    }

    /**
     * 线缆统计-类别
     *
     * @param
     * @return
     */
    @ApiOperation("线缆统计-类别")
    @PostMapping("/getTypeCount")
    public ActionResult getTypeCount() throws IOException {
        //树形判断是否有参数，有参数不造树
        long count = lineLineService.getTypeCount();
        return ActionResult.success(count);
    }

    /**
     * 列表
     *
     * @param lineLinePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody LineLinePagination lineLinePagination) throws IOException {
        PageListVO vo = new PageListVO();
        //1.查询主表数据
        List<LineLineEntity> list = lineLineService.getList(lineLinePagination);
        if(ListUtil.isEmpty(list)){
            PaginationVO page = JsonUtil.getJsonToBean(lineLinePagination, PaginationVO.class);
            vo.setPagination(page);
            vo.setList(new ArrayList());
            return ActionResult.success(vo);
        }

        List<String> lineIdList = list.stream().map(t -> t.getId()).collect(Collectors.toList());
        Map<String, List<String>> releationMapList = new HashMap<>();
        Map<String, List<String>> placeNameMapList = new HashMap<>();

        Map<String, List<LinePlaceEntity>> placeMapList = lineLinePlaceRelationService.getPlaceMapListByLineIdList(lineIdList);
        placeMapList.forEach((k,v)->{
            releationMapList.put(k,ListUtil.subList(v,LinePlaceEntity::getId));
            placeNameMapList.put(k,ListUtil.subList(v,LinePlaceEntity::getName));
        });


        List<LineLineListVO> listVO = JsonUtil.getJsonToList(list, LineLineListVO.class);
        for (LineLineListVO lineLineVO : listVO) {
            lineLineVO.setPath(releationMapList.get(lineLineVO.getId()));
            lineLineVO.setPath_name(placeNameMapList.get(lineLineVO.getId()));
            lineLineVO.setCode_name(lineLineVO.getCode());
            lineLineVO.setName_name(lineLineVO.getName());
            lineLineVO.setDepth_name(lineLineVO.getDepth());
            lineLineVO.setCreatetime_name(lineLineVO.getCreatetime() != null ?
                    new Date(lineLineVO.getCreatetime()) : null);
            lineLineVO.setUnit_name(lineLineVO.getUnit());
            lineLineVO.setUse_name(lineLineVO.getUse());
            lineLineVO.setLength_name(lineLineVO.getLength());
            lineLineVO.setMaterial_name(lineLineVO.getMaterial());
            lineLineVO.setElectric_name(lineLineVO.getElectric());
            lineLineVO.setRemark_name(lineLineVO.getRemark());
        }
        dataDicUtil.replaceCodeWithName(listVO,"747488030398350149", LineLineListVO::getType,LineLineListVO::setType_name);
        dataDicUtil.replaceCodeWithName(listVO,"743830875539505221", LineLineListVO::getStatus,LineLineListVO::setStatus_name);
        dataDicUtil.replaceCodeWithName(listVO,"743830947396321349", LineLineListVO::getStatuswork,LineLineListVO::setStatuswork_name);

        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(lineLinePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param lineLineForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid LineLineForm lineLineForm) throws DataException {
        ActionResult actionResult = lineLineService.checkForm(lineLineForm, "0");
        if (actionResult.getCode()!=200) {
            return actionResult;
        }
        String mainId = RandomUtil.uuId();

        LineLineEntity entity = JsonUtil.getJsonToBean(lineLineForm, LineLineEntity.class);
        entity.setId(mainId);
        entity.setCreatetime(new Date());
        lineLineService.save(entity);
        List<String> placeIdList = lineLineForm.getPath();
        if(ListUtil.isEmpty(placeIdList)){
            return ActionResult.success("创建成功");
        }
        List<String> entityPlaceIdList =
                ListUtil.subList(
                        linePlaceService.listByIds(placeIdList.stream().distinct().collect(Collectors.toList()))
                        ,LinePlaceEntity::getId
                );

        if(ListUtil.isEmpty(entityPlaceIdList)){
            return ActionResult.success("创建成功");
        }
        AtomicInteger index= new AtomicInteger();
        List<LineLinePlaceRelationEntity> lineLinePlaceRelationEntityList =
                placeIdList
                        .stream()
                        .filter(placeId->StringUtil.isNotEmpty(placeId)&&entityPlaceIdList.contains(placeId))
                        .map(s->{
            return new LineLinePlaceRelationEntity().setLineId(entity.getId()).setPlaceId(s).setPathIndex(index.incrementAndGet());

        }).collect(Collectors.toList());
        if(ListUtil.isEmpty(lineLinePlaceRelationEntityList)){
            return ActionResult.success("创建成功");
        }
        lineLinePlaceRelationService.saveBatch(lineLinePlaceRelationEntityList);


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<LineLineInfoVO> info(@PathVariable("id") String id) {
        LineLineEntity entity = lineLineService.getById(id);
        LineLineInfoVO vo = JsonUtil.getJsonToBean(entity, LineLineInfoVO.class);
        List<String> placeIdList = lineLinePlaceRelationService.getPlaceIdListByLineId(id);
        vo.setPath(JsonUtil.getObjectToString(placeIdList));

        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<LineLineListVO> detailInfo(@PathVariable("id") String id) {
        LineLineEntity entity = lineLineService.getById(id);
        LineLineListVO vo = JsonUtil.getJsonToBean(entity, LineLineListVO.class);

        List<LinePlaceEntity> placeList = lineLinePlaceRelationService.getPlaceListByLineId(id);
        List<String> placeIdList= new ArrayList<>();
        List<String> placeNameList= new ArrayList<>();
        for (LinePlaceEntity placeEntity : placeList) {
            placeIdList.add(placeEntity.getId());
            placeNameList.add(placeEntity.getName());

        }

        vo.setPath(placeIdList);
        vo.setPath_name(placeNameList);
        vo.setCode_name(vo.getCode());
        vo.setName_name(vo.getName());
        vo.setDepth_name(vo.getDepth());
        vo.setCreatetime_name(vo.getCreatetime() != null ?
                new Date(vo.getCreatetime()) : null);
        vo.setUnit_name(vo.getUnit());
        vo.setUse_name(vo.getUse());
        vo.setLength_name(vo.getLength());
        vo.setMaterial_name(vo.getMaterial());
        vo.setElectric_name(vo.getElectric());
        vo.setRemark_name(vo.getRemark());

        vo.setType_name(generaterSwapUtil.getDicName(vo.getType(), "747488030398350149"));
        vo.setStatus_name(generaterSwapUtil.getDicName(vo.getStatus(), "743830875539505221"));
        vo.setStatuswork_name(generaterSwapUtil.getDicName(vo.getStatuswork(), "743830947396321349"));
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param lineLineForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid LineLineForm lineLineForm) throws DataException {
        ActionResult actionResult = lineLineService.checkForm(lineLineForm, id);
        if (actionResult.getCode()!=200) {
            return actionResult;
        }
        LineLineEntity entity = lineLineService.getById(id);
        if (entity != null) {
            LineLineEntity subentity = JsonUtil.getJsonToBean(lineLineForm, LineLineEntity.class);
            boolean b1 = lineLineService.updateById(subentity);
            QueryWrapper<LineLinePlaceRelationEntity> reQueryWrapper = new QueryWrapper<>();
            reQueryWrapper.lambda().eq(LineLinePlaceRelationEntity::getLineId,entity.getId());
            lineLinePlaceRelationService.remove(reQueryWrapper);

            List<String> placeIdList = lineLineForm.getPath();
            if(ListUtil.isEmpty(placeIdList)){
                return ActionResult.success("创建成功");
            }
            List<String> entityPlaceIdList =
                    ListUtil.subList(
                            linePlaceService.listByIds(placeIdList.stream().distinct().collect(Collectors.toList()))
                            ,LinePlaceEntity::getId
                    );

            if(ListUtil.isEmpty(entityPlaceIdList)){
                return ActionResult.success("创建成功");
            }
            AtomicInteger index= new AtomicInteger();
            List<LineLinePlaceRelationEntity> lineLinePlaceRelationEntityList =
                    placeIdList
                            .stream()
                            .filter(placeId->StringUtil.isNotEmpty(placeId)&&entityPlaceIdList.contains(placeId))
                            .map(s->{
                                return new LineLinePlaceRelationEntity().setLineId(entity.getId()).setPlaceId(s).setPathIndex(index.incrementAndGet());
                            }).collect(Collectors.toList());
            if(ListUtil.isEmpty(lineLinePlaceRelationEntityList)){
                return ActionResult.success("创建成功");
            }
            lineLinePlaceRelationService.saveBatch(lineLinePlaceRelationEntityList);

            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 大屏更新
     *
     * @param id
     * @param lineLineForm
     * @return
     */
    @PutMapping("/dp/{id}")
    @Transactional
    @ApiOperation("大屏更新")
    public ActionResult updateDp(@PathVariable("id") String id, @RequestBody @Valid LineLineForm lineLineForm) throws DataException {
        ActionResult actionResult = lineLineService.checkForm(lineLineForm, id);
        if (actionResult.getCode()!=200) {
            return actionResult;
        }
        LineLineEntity entity = lineLineService.getById(id);
        if (entity != null) {
            entity.setName(lineLineForm.getName());
            entity.setType(lineLineForm.getType());
            entity.setCode(lineLineForm.getCode());
            entity.setPath(JsonUtil.getObjectToString(lineLineForm.getPath()));
            QueryWrapper<LineLinePlaceRelationEntity> reQueryWrapper = new QueryWrapper<>();
            reQueryWrapper.lambda().eq(LineLinePlaceRelationEntity::getLineId,entity.getId());
            lineLinePlaceRelationService.remove(reQueryWrapper);

            List<String> placeIdList = lineLineForm.getPath();
            if(ListUtil.isEmpty(placeIdList)){
                return ActionResult.success("创建成功");
            }
            List<String> entityPlaceIdList =
                    ListUtil.subList(
                            linePlaceService.listByIds(placeIdList.stream().distinct().collect(Collectors.toList()))
                            ,LinePlaceEntity::getId
                    );

            if(ListUtil.isEmpty(entityPlaceIdList)){
                return ActionResult.success("创建成功");
            }
            List<LineLinePlaceRelationEntity> lineLinePlaceRelationEntityList =
                    placeIdList
                            .stream()
                            .filter(placeId->StringUtil.isNotEmpty(placeId)&&entityPlaceIdList.contains(placeId))
                            .map(s->{
                                return new LineLinePlaceRelationEntity().setLineId(entity.getId()).setPlaceId(s);
                            }).collect(Collectors.toList());
            if(ListUtil.isEmpty(lineLinePlaceRelationEntityList)){
                return ActionResult.success("创建成功");
            }
            lineLinePlaceRelationService.saveBatch(lineLinePlaceRelationEntityList);
            boolean b1 = lineLineService.updateById(entity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        lineLineService.removeById(id);
        return ActionResult.success("删除成功");
    }

    /**
     * 根据线缆查询管井列表
     *
     * @param id
     * @return
     */
    @ApiOperation("根据线缆查询管井列表")
    @GetMapping("/getPlaceListByLineId/{id}")
    @Transactional
    public ActionResult getPlaceListByLineId(@PathVariable("id") String id){
        List<LinePlaceEntity> linePlaceEntityList = lineLineService.getPlaceListByLineId(id);
        return ActionResult.success(linePlaceEntityList);
    }
}
